package com.hardson.toolkit.swing.table;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicTableUI;
import javax.swing.table.TableCellRenderer;

class DTableUI extends BasicTableUI {
	@Override
	public void paint(final Graphics g, final JComponent c) {
		//		Rectangle r = g.getClipBounds();
		//		int firstRow = table.rowAtPoint(new Point(0, r.y));
		//		int lastRow = table.rowAtPoint(new Point(0, r.y + r.height));
		//		if (lastRow < 0)
		//			lastRow = table.getRowCount() - 1;
		//		for (int i = firstRow; i <= lastRow; i++)
		//			paintRow(i, g);
		for (int i = 0; i < this.table.getRowCount(); i++) {
			this.paintRow(i, g);
		}
	}

	private void paintRow(final int row, final Graphics g) {
		Rectangle clipBounds = g.getClipBounds();
		GridSplit gridSplit = ((DTable) this.table).getGridSplit();
		for (int i = 0; i < this.table.getColumnCount(); i++) {
			if (gridSplit.isVisible(row, i)) {
				Rectangle rec = this.table.getCellRect(row, i, true);
				System.out.println(rec.x + " " + rec.y + " " + rec.width + " " + rec.height);
				if (rec.intersects(clipBounds)) {
					this.paintCell(row, i, g, rec);
				}
			}
		}
	}

	private void paintCell(final int row, final int column, final Graphics g,
			final Rectangle area) {
		int verticalMargin = this.table.getRowMargin();
		int horizontalMargin = this.table.getColumnModel().getColumnMargin();

		Color c = g.getColor();
		g.setColor(this.table.getGridColor());
		//g.drawRect(area.x , area.y, area.width - 1, area.height - 1);
		g.drawRect(area.x, area.y - 1, area.width, area.height);
		g.setColor(c);

		area.setBounds(area.x + horizontalMargin / 2, area.y + verticalMargin / 2,
				area.width - horizontalMargin, area.height - verticalMargin);

		if (this.table.isEditing() && this.table.getEditingRow() == row
				&& this.table.getEditingColumn() == column) {
			Component component = this.table.getEditorComponent();
			component.setBounds(area);
			component.validate();
		} else {
			TableCellRenderer renderer = this.table.getCellRenderer(row, column);
			Component component = this.table.prepareRenderer(renderer, row, column);
			if (component.getParent() == null) {
				this.rendererPane.add(component);
			}
			this.rendererPane.paintComponent(g, component, this.table, area.x, area.y, area.width,
					area.height, true);
			//			System.out.println(area.x + " " + area.y + " " + area.width + " " + area.height);
		}
	}

}
